/*
Copyright 2021 LuJun

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is furnished 
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

/// <reference path="../../log/log-manager.ts" />
/// <reference path="../../utils/js.ts" />

namespace lcc {

const http = require('http');
const https = require('https');

const TAG = "lcc/network/http/web-server.ts";

/**
 * @zh
 * WEB服务器配置
 */
export interface WebServerConfig {
	/**
     * @zh
	 * 名称
	 */
	name:string;

	/**
     * @zh
	 * 实体对象
	 */
	entity:any;

	/**
     * @zh
	 * 端口
	 */
	port:number;

	/**
     * @zh
	 * https配置
	 */
	tslConfig?:TSLConfig;
}

/**
 * @zh
 * WEB服务器映射表
 */
export let WEBSERVERS:{[key:string]:WebServerConfig} = js.createMap();

/**
 * @zh
 * WEB服务器管理<br/>
 * 快速搭建游戏类web服务器:<br/>
 * ```  
 *      // 这样通过`lcc.express.createFileDownloadExpress`快速创建文件下载服务器
 *      lcc.webServer.addServer('test', lcc.express.createFileDownloadExpress('F://'), 4000, { ...https配置... });
 * ```
 */
export class WebServer extends cocos.event.EventTarget {

	/**
     * @zh
	 * 单例实例
	 */
	private static _instance : WebServer;

	/**
     * @zh
	 * 获取单例对象
	 */
	public static getInstance() : WebServer  {
		if(!WebServer._instance){
			WebServer._instance = new WebServer();
		}
		return WebServer._instance
	}
	
	/**
     * @zh
	 * 添加服务器
     * 
	 * @param name - 名称
	 * @param express - Express对象
	 * @param port - 端口
	 * @param tslConfig - https配置
	 */
	public addServer(name:string, express:any, port:number, tslConfig?:TSLConfig){
		return new Promise<WebServerConfig>((resolve)=>{
			DEBUG.NETWORK && logMgr.debug(TAG, `addServer ${name} ${port}`);
			if(WEBSERVERS[name]){
				logMgr.error(TAG, `server [${name}] conflict!`);
				resolve(null);
			}else{
				express.set('port', port);
				express.set('server', name);
				let server = null;
				if(tslConfig){
					server = https.createServer(tslConfig, express);
				}else{
					server = http.createServer(express);
				}
				server.on('error', (error)=>{
					if (error.syscall == 'listen') {
						let bind = typeof port === 'string'
						? 'Pipe ' + port
						: 'Port ' + port;
						
						// handle specific listen errors with friendly messages
						switch (error.code) {
							case 'EACCES':
								logMgr.error(TAG, bind + ' requires elevated privileges');
								break;
							case 'EADDRINUSE':
								logMgr.error(TAG, bind + ' is already in use');
								break;
							default:
						}
						resolve(null);
					}
				});
				server.on('listening', ()=>{
					let addr = server.address();
					let bind = typeof addr === 'string'
					? 'pipe ' + addr
					: 'port ' + addr.port;
					DEBUG.NETWORK && logMgr.debug(TAG, `${name} SERVER listening ${bind}`);

					let svrconfig:WebServerConfig = {
						name : name,
						entity : server,
						port : port,
						tslConfig : tslConfig,
					};
					WEBSERVERS[name] = svrconfig;
					resolve(svrconfig);
				});
				server.listen(port);
			}
		});
	}

	/**
     * @zh
	 * 获得服务器
     * 
	 * @param name - 名称
	 */
	public getServer(name:string){
		return WEBSERVERS[name];
	}

	/**
     * @zh
	 * 移除服务器
     * 
	 * @param name - 名称
	 */
	public removeServer(name:string){
		DEBUG.NETWORK && logMgr.debug(TAG, `removeServer ${name}`);
		let svrconfig = WEBSERVERS[name];
		if(svrconfig){
			delete WEBSERVERS[name];
			svrconfig.entity.close();
			DEBUG.NETWORK && logMgr.debug(TAG, `removeServer ${name} success`);
		}
	}

	/**
	 * @zh
	 * 移除所有服务器
	 */
	public removeAllServers(){
		DEBUG.NETWORK && logMgr.debug(TAG, `removeAllServers`);
		for(let sname of Object.keys(WEBSERVERS)){
			this.removeServer(sname);
		}
	}
}

/**
 * @zh
 * WEB服务器管理实例
 */
export const webServer = WebServer.getInstance();

}
